$(function () {
    var url = window.location.search.substring(1);
    var id = url.substring(url.lastIndexOf("=") + 1);
    $("#id").html(id);
    $.ajax({
        url: "/vote/init/" + id,
        type: "post",
        data: "",
        dataType: "json",
        success: function (data) {
            $("#title").html(data.sub.title);
            $("#view").html(data.sub.viewTimes);
            $("#vote").html(data.sub.totalVotes);
            var str = "<table>";
            $.each(data.opt, function (i) {
                str += "<tr>" +
                    "<td>" + (i + 1) + "</td>" +
                    "<td><input type='radio' name='opt' value='" + this.id + "'/>" + this.optContent + "</td>" +
                    "<td>" + this.vote + "票</td>" +
                    "<td>" + (Math.round(this.vote * 1000 / data.sub.totalVotes)) / 10 + "%</td>"
            })
            str += "</table>";
            $("#show").html(str);
        }
    })

    $("#btn").click(function () {
        var optId = 0;
        var opts = $("input[type=radio]");
        $.each(opts, function () {
            if ($(this).is(":checked")) {
                optId = $(this).val();
            }
        })
        if (optId == 0) {
            alert("请从列表中选择一项已完成投票！");
        } else {
            var id = $("#id").html();
            $.ajax({
                url: "/vote/votes",
                type: "post",
                data: {"id": optId, "sid": id},
                dataType: "json",
                success: function (data) {
                    if (data == true) {
                        voteF(id);
                    }
                }
            });
        }
    });

    function voteF(id) {
        $.ajax({
            url: "/vote/showOptions/" + id,
            type: "post",
            data: "",
            dataType: "json",
            success: function (data) {
                var voteCount = parseInt($("#vote").html()) + 1;
                var str = "<table>";
                $.each(data, function (i) {
                    str += "<tr>" +
                        "<td>" + (i + 1) + "</td>" +
                        "<td>" + this.optContent + "</td>" +
                        "<td>" + this.vote + "票</td>" +
                        "<td>" + (Math.round(this.vote / voteCount * 1000) / 10) + "%</td>"
                    "</tr>"
                });
                str += "</table>";
                $("#vote").html(voteCount);
                $("#show").html(str);
                $("#btn").hide();
            }
        });
    }
})